public class Solution {
    public String reverseStr(String S, int k) {
        char[] s = S.toCharArray();
        int n = s.length;
        for (int i = 0; i < n; i += k * 2) {
            reverse(s, i, Math.min(i + k, n) - 1);
        }
        return new String(s);
    }

    private void reverse(char[] s, int left, int right) {
        while (left < right) {
            char tmp = s[left];
            s[left++] = s[right];
            s[right--] = tmp;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        String str1 = "abcdefg";
        int k = 2;
        System.out.println("输入: " + str1 + ", k = " + k);
        System.out.println("输出: " + solution.reverseStr(str1, k)); // 输出: "bacdfeg"
    }
}
